const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config");

exports.getUserInfo = (req, res) => {
  const sql = `select id, user_name, nick_name, email, user_pic from tf_user where id=?`;
  console.log(req.auth);
  db.query(sql, req.auth.id, (err, results) => {
    if (err) return res.json({ status: 1, message: err.message });
    if (results.length !== 1)
      return res.json({ status: 1, message: "获取用户信息失败" });
    res.send({
      status: 0,
      message: "获取用户信息成功",
      data: results[0],
    });
  });
};

exports.updateUserInfo = (req, res) => {
  // 定义字段映射关系
  const updateData = {
    nick_name: req.body.nickname,
    email: req.body.email,
  };
  const sql = `update tf_user set ? where id=?`;
  db.query(sql, [updateData, req.auth.id], (err, results) => {
    if (err) return res.json({ status: 1, message: err.message });
    if (results.affectedRows !== 1)
      return res.json({ status: 1, message: "更新用户信息失败" });
    res.json({ status: 0, message: "更新用户信息成功" });
  });
};

exports.updatePassword = (req, res) => {
  // 1. 获取用户输入的原密码和修改后的密码
  const user = req.body;
  // 2. 对用户输入的原密码进行验证
  const sql = `select * from tf_user where id=?`;
  db.query(sql, req.auth.id, (err, results) => {
    if (err) return res.json({ status: 1, message: err.message });
    if (results.length !== 1)
      return res.json({ status: 1, message: "用户不存在" });
    const compareResult = bcrypt.compareSync(user.oldPwd, results[0].password);
    if (!compareResult) return res.json({ status: 1, message: "原密码错误" });
    const sql = `update tf_user set password=? where id=?`;
    user.newPwd = bcrypt.hashSync(user.newPwd, 10);
    db.query(sql, [user.newPwd, req.auth.id], (err, results) => {
      if (err) return res.json({ status: 1, message: err.message });
      if (results.affectedRows !== 1)
        return res.json({ status: 1, message: "更新密码失败" });
      return res.json({ status: 0, message: "更新密码成功" });
    });
  });
};

exports.updateAvatar = (req, res) => {
  const sql = `update tf_user set user_pic=? where id=?`;
  db.query(sql, [req.body.avatar, req.auth.id], (err, results) => {
    if (err) return res.json({ status: 1, message: err.message });
    if (results.affectedRows !== 1)
      return res.json({ status: 1, message: "更新头像失败"})
    return res.json({ status: 0, message: "更新头像成功"})
  })
}
